
import React, { PureComponent } from 'react'
import { Form, Input, Button, Radio, Row, Col, Checkbox } from 'antd';
import { connect } from 'react-redux'
const FormItem = Form.Item;
import {CloseOutlined} from "@ant-design/icons";
import dayjs from "dayjs";
import PageBackHeader from "@common/PageBackHeader";
import { withRouter } from 'react-router-dom'
import { getBilinInfo } from "@utils/localStorage";
import { PROMOTION_NAME_TYPE } from '@constants/ActivityListMap'
import DateRangePicker from "@common/presentational/DateRangePicker";
import { updatePromotion, createPromotion, publishPromotion } from "@sagas/marketing";
import { getHistoryMatchParams } from "@utils/setUrlQuery";
import { MultiSelectShelfProductModal } from "@common/presentational/MultiSelectModal";
import GradientRules from '@components/marketing/GradientRules'
import {priceFenToYuan, priceYuanToFen} from "@utils/priceConversion";
import RepeatDate from '@components/marketing/RepeatDate'
import InputNumberWithSuffix from "@common/presentational/InputNumberWithSuffix";
import notify from "@utils/tip";
const getReformedData = (data) => {
    const _data = {
        ...data,
        price: data.offer_type === 'quota_cut' ? priceFenToYuan(data.price) : data.price / 10,
        off_maximum: data.off_maximum ? priceFenToYuan(data.off_maximum) : '',
        quota: data.quota ? priceFenToYuan(data.quota) : '',
        use_time: {
            startDate: dayjs(data.begined),
            endDate: dayjs(data.ended),
        },
        quota_type: data.gradient_rules.length ? 'gradient' : 'cycle',
        repeat_date_value:{
            type: data.weekdays.length ? 'weeks' : (data.monthdays.length ? 'months' :( data.time_ranges.length ? 'days' : '')),
            times: data.time_ranges || [],
            weekdays: data.weekdays || [],
            monthdays: data.monthdays || [],
        },
        repeat_date: data.weekdays.length || data.monthdays.length || data.time_ranges.length
    }
    return {
        ..._data
    }
}

const initialValue = {
    name: '',
    scope: 'unlimited',
    gradient_rules: [],
    repeat_date_value:{},
    repeat_date:false
}
@connect(
    null
    , {
        updatePromotion,
        createPromotion,
        publishPromotion
    })
@withRouter
class MarketingPromotionCreate extends PureComponent {

    constructor(props) {
        super(props);
        const { location } = props
        const { id, type } = getHistoryMatchParams(props)
        const { state } = location
        this.state = {
            id,
            type,
            formData: id ? {
                ...initialValue,
                ...getReformedData(state),
            } : {
                ...initialValue
            },
            productInfoList: id ? state.item_confs : []
        }

        this.formRef = React.createRef()
        this.multiSelectModalRef = React.createRef()

        this.handleSubmit = this.handleSubmit.bind(this)
        this.submitForm = this.submitForm.bind(this)
        this.cancelFunc = this.cancelFunc.bind(this)
    }

    showAddProductModal() {
        this.multiSelectModalRef.current?.show()
    }

    handleSubmit(values) {
        const { id, type, productInfoList } = this.state
        const { updatePromotion, createPromotion, publishPromotion } = this.props
        const pStoreId = getBilinInfo('storeId') || 0
        const owner_type = pStoreId ? 'store' : 'brand'
        const owner_id = pStoreId
        const params = {
            owner_type,
            owner_id,
            name: values.name,
            nature: 'item_off',
            offer_category: 'preferential',
            offer_type: type,
            issuer: 'emall',
            need_verify_qualification: false,
            use_scenes: ['ordering'],
            scope: values.scope,
        }
        if (type === 'quota_cut' && values.quota_type === 'cycle') {
            params.quota =  priceYuanToFen(values.quota)
            params.price =  priceYuanToFen(values.price)
        }
        if (type === 'quota_cut' && values.quota_type === 'gradient') {
            params.gradient_rules = values.gradient_rules
        }
        if (type === 'discount') {
            params.price = parseInt(values.price * 10)
        }
        if (type === 'discount' && values.off_maximum) {
            params.off_maximum = priceYuanToFen(values.off_maximum)
        }
        params.begined = new Date(values.use_time.startDate).toISOString()
        params.ended = new Date(values.use_time.endDate).toISOString()
        if(values.repeat_date && values.repeat_date_value){
            if(values.repeat_date_value.times && values.repeat_date_value.times.length && !values.repeat_date_value.begin_at){
                params.time_ranges = [{
                    begin_at:values.repeat_date_value.times[0].begin_at || '00:00',
                    end_at:values.repeat_date_value.times[0].end_at || '00:00',
                }]
            }else{
                params.time_ranges = [{
                    begin_at:values.repeat_date_value.begin_at || '00:00',
                    end_at:values.repeat_date_value.end_at || '00:00',
                }]
            }
            if(values.repeat_date_value.type ==='weeks'){
                params.weekdays = values.repeat_date_value.weekdays
                params.date_choose_type = 'include'
            }
            if(values.repeat_date_value.type ==='months'){
                params.monthdays = values.repeat_date_value.monthdays
                params.date_choose_type = 'include'
            }
        }
        if(values.scope === 'include_items'){
            if(!productInfoList.length){
                notify('请选择商品', 'error')
                return false
            }
            params.item_confs = productInfoList
        }
        if(values.scope === 'exclude_items'){
            if(!productInfoList.length){
                notify('请选择商品', 'error')
                return false
            }
            params.item_confs = productInfoList
        }
        if (id) {
            params.id = id
            updatePromotion(params, () => {
                this.cancelFunc()
            })
        } else {
            const that = this
            createPromotion(params, (res) => {
                publishPromotion({
                    id: res.promotion?.id
                }, () => {
                    that.cancelFunc()
                })
            })
        }
    }

    handleMinus(rule, value,callback) {
        let noValue = false; // 活动规则不能为空
        let valueError = false // 活动需满金额需要大于活动可减金额
        if (Array.isArray(value)) {
            value.forEach(v => {
                if (!v.quota || !v.price) {
                    noValue = true
                } else if (v.quota <= v.price) {
                    valueError = true
                }
            })
        } else if (typeof (value) === 'object') {
            if (!value.quota || !value.price) {
                noValue = true
            } else if (value.quota <= value.price) {
                valueError = true
            }
        }
        if (noValue || valueError) {
            callback(`${noValue ? '活动规则不能为空' : '订单金额需要大于可减金额'}`)
        } else {
            callback()
        }
    }

    submitForm() {
        this.formRef.current?.submit()
    }

    cancelFunc() {
        this.props.goBack ? this.props.goBack() : this.props.history.goBack()
    }

    deleteItems(index){
        this.setState({
            productInfoList:[
                ...this.state.productInfoList.slice(0, index),
                ...this.state.productInfoList.slice(index + 1)
            ]
        })
    }

    handleProductChange(value) {
        this.setState({
            productInfoList: value
        })
    }
    render() {
        const { formData, id, type, productInfoList } = this.state
        const isEdit = !!id
        return (
            <div className="bilin-web">
                <PageBackHeader title={isEdit ? `编辑${PROMOTION_NAME_TYPE[type]}` : `新建${PROMOTION_NAME_TYPE[type]}`} />
                <div className="bilin-web-body form-page with-footer">
                    <Form
                        ref={this.formRef}
                        name="promotion-form"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={formData}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                        onFinish={this.handleSubmit}
                    >
                        <div className="ft-16 pdb-36">基本信息</div>
                        <FormItem
                            label="活动名称: "
                            name='name'
                            rules={[
                                { required: true, message: '请输入名称', },
                            ]}
                        >
                            <Input placeholder={ type ==='quota_cut'? "如：新品满减，最多24个字" : "如：新品限时折扣，最多24个字"} maxLength={24} />
                        </FormItem>
                        <FormItem
                            label="活动时间: "
                            name='use_time'
                            rules={[
                                { required: true, message: '请选择使用时间', },
                            ]}
                        >
                            <DateRangePicker />
                        </FormItem>
                        <Row className='flex-vertical-center'>
                            <Col span={4} />
                            <Col span={20}>
                                <FormItem
                                    name='repeat_date'
                                    noStyle
                                    valuePropName="checked"
                                    rules={[
                                        { required: false },
                                    ]}
                                >
                                    <Checkbox>
                                        按周期重复
                                    </Checkbox>
                                </FormItem>
                            </Col>
                        </Row>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.repeat_date !== currentValues.repeat_date}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('repeat_date') ? (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        <Col span={20}>
                                        <FormItem
                                            name='repeat_date_value'
                                            noStyle
                                            rules={[
                                                { required: false, },
                                            ]}
                                        >
                                            <RepeatDate />
                                        </FormItem>
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <div className="ft-16 pdb-36">活动规则</div>
                        {
                            type === 'quota_cut' && <>
                                <FormItem
                                    label="优惠方式: "
                                    name='quota_type'
                                    rules={[
                                        { required: true, message: '请选择优惠方式', },
                                    ]}
                                >
                                    <Radio.Group>
                                        <Radio value='gradient'>阶梯满减</Radio>
                                        <Radio value='cycle'>循环满减</Radio>
                                    </Radio.Group>
                                </FormItem>
                                <Form.Item
                                    noStyle
                                    shouldUpdate={(prevValues, currentValues) => prevValues.quota_type !== currentValues.quota_type}
                                >
                                    {({ getFieldValue }) => {
                                        return (<>
                                            <Row className='flex-vertical-center'>
                                                <Col span={4} />
                                                {getFieldValue('quota_type') === 'cycle' && <>
                                                    <Col span={2}>
                                                        <span>订单每满</span>
                                                    </Col>
                                                    <Col span={8}>
                                                        <FormItem
                                                            name='quota'
                                                            noStyle
                                                            rules={[
                                                                { required: true, message: '请输入金额', },
                                                            ]}
                                                        >
                                                            <InputNumberWithSuffix 
                                                                min={0.01}
                                                                max={100000}
                                                                step={1}
                                                                precision={2}
                                                                placeholder="请输入金额" 
                                                                style={{ width: '200px' }}
                                                                suffix={(
                                                                    <span>元</span>
                                                                )}
                                                            />
                                                        </FormItem>
                                                    </Col>
                                                    <Col span={2}>
                                                        <span className='mgl-8'>立减</span>
                                                    </Col>
                                                    <Col span={8}>
                                                        <FormItem
                                                            name='price'
                                                            noStyle
                                                            rules={[
                                                                { required: true, message: '请输入金额', },
                                                            ]}
                                                        >
                                                            <InputNumberWithSuffix 
                                                                min={0.01}
                                                                max={100000}
                                                                step={1}
                                                                precision={2}
                                                                placeholder="请输入金额" 
                                                                style={{ width: '200px' }}
                                                                suffix={(
                                                                    <span>元</span>
                                                                )}
                                                            />
                                                        </FormItem>
                                                    </Col>
                                                </>}
                                                {getFieldValue('quota_type') === 'gradient' && <>
                                                    <Col span={20}>
                                                        <FormItem
                                                            name='gradient_rules'
                                                            // noStyle
                                                            rules={[
                                                                { required: true, message: '请设置阶梯满减规则', },
                                                                { validator: this.handleMinus, }
                                                            ]}
                                                        >
                                                            <GradientRules />
                                                        </FormItem>
                                                    </Col>
                                                </>}

                                            </Row>
                                        </>
                                        )
                                    }}
                                </Form.Item>
                            </>
                        }
                        {type === 'discount' && <>
                            <FormItem
                                label='折扣优惠:'
                                name='price'
                                rules={[
                                    { required: true, message: '请输入折扣', },
                                ]}
                            >
                                <InputNumberWithSuffix 
                                    min={0.1}
                                    max={9.9}
                                    step={1}
                                    precision={1}
                                    placeholder="请输入折扣" 
                                    style={{ width: '200px' }}
                                    suffix={(
                                        <span>折</span>
                                    )}
                                />
                            </FormItem>
                            <FormItem
                                label='折扣优惠上限:'
                                name='off_maximum'
                                rules={[
                                    { required: true, message: '请输入折扣上限' },
                                ]}
                            >
                                <InputNumberWithSuffix 
                                    min={0.01}
                                    max={100000}
                                    step={1}
                                    precision={2}
                                    placeholder="请输入" 
                                    style={{ width: '200px' }}
                                    suffix={(
                                        <span>元</span>
                                    )}
                                />
                            </FormItem>
                        </>}
                        <FormItem
                            label="适用商品: "
                            name='scope'
                            rules={[
                                { required: true, message: '请选择类型', },
                            ]}
                        >
                            <Radio.Group>
                                <Radio value='unlimited'>全部商品</Radio>
                                <Radio value='include_items'>指定商品可用</Radio>
                                <Radio value='exclude_items'>指定商品不可用</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.scope !== currentValues.scope}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('scope') !== 'unlimited' ? (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        <Col span={20}>
                                            <Button type="primary" ghost onClick={this.showAddProductModal.bind(this)}>+ 添加商品</Button>
                                            {productInfoList.length ? <div className='mgt-16 market-product-list'>
                                                {productInfoList.map((item,index)=>(<div key={index} className='market-product-item'>
                                                    <div>{item.name}</div>
                                                    <div>
                                                        <CloseOutlined className="cur-poi ft-12 ft-clr-ml" onClick={this.deleteItems.bind(this, index)} />
                                                    </div>
                                                </div>))}
                                            </div> : null}
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button type="primary" ghost onClick={this.cancelFunc}>取消</Button>
                    <Button type="primary" onClick={this.submitForm}>保存</Button>
                </div>
                <MultiSelectShelfProductModal
                    ref={this.multiSelectModalRef}
                    title="添加商品"
                    onChange={this.handleProductChange.bind(this)}
                    initSelectedInfo={productInfoList}
                />
            </div>
        )
    }
}

export default MarketingPromotionCreate